
function utilAlert(msg, iconType) {
    uni.showToast({
        title: msg == null ? "" : msg,
        icon: "none",
        duration: 1500
    });
    return;
};

function utilLoading(tip,mask){
    uni.showLoading({
        title: tip?tip:'加载中',
        mask:mask?mask:false
    });

    setTimeout(function (){
         uni.hideLoading();
    },10000)
};
//  ['vuex_userInfo', 'vuex_token','vuex_deviceMode','vuex_loginParam'];
function clearVuex(that){
	console.log("清除缓存");
	that.$u.vuex('vuex_userInfo',{});
	that.$u.vuex('vuex_token','');
	that.$u.vuex('vuex_loginParam.password','');
	that.$u.vuex('vuex_loginParam.userDeviceId','');
	that.$u.vuex('circleData',[]);
	uni.clearStorageSync();
}
function clearStorageVuex(that){
	that.$u.vuex('circleData',[]);
	that.$u.vuex('circleBgImg',"");
	utilAlert("清除成功");
}

function palyMsgTips(){
	let innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = false;
	innerAudioContext.src = "/static/mp3/msgTip2.mp3";
	innerAudioContext.startTime = 0;
	innerAudioContext.onPlay(() => {
	 // console.log('开始播放');
		uni.vibrateLong({})
	});
	innerAudioContext.onError((res) => {
	  //console.log(res.errMsg);
	  //console.log(res.errCode);
	 // innerAudioContext.destroy()
	});
	innerAudioContext.onEnded(function(){
		// console.log('结束播放,摧毁');
		 innerAudioContext.destroy();
	})
	innerAudioContext.onStop(function(){
		//  console.log('停止播放,摧毁');
		 innerAudioContext.destroy();
	})
	innerAudioContext.play();

}

function palyMsgTipSelected(that,chatGroupId){
	let currentUserId= that.vuex_userInfo.id;
	let param={
		chatGroupId:chatGroupId,
		userId:currentUserId
	};
	that.$u.api.chatGroup.getChatPingBiFlag(param).then(res => {
		//console.log("获取是否屏蔽消息标志的结果",res);
		if(res.code==200&&res.data==true){
				//没有屏蔽,提示音提示
				palyMsgTips();
		}
		else{
			return;
		}
	}).catch(res => {
	  console.log("清除未读数量接口请求失败");
	});
}

//字节转换
function byteConvert(bytes) {
      //console.log("字节量"+bytes);
      if (isNaN(bytes)) {
        return '';
      }
      var symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var exp = Math.floor(Math.log(bytes)/Math.log(2));
      if (exp < 1) {
        exp = 0;
      }
      var i = Math.floor(exp / 10);
      bytes = bytes / Math.pow(2, 10 * i);
      if (bytes.toString().length > bytes.toFixed(2).toString().length) {
        bytes = bytes.toFixed(2);
      }
      return bytes + ' ' + symbols[i];
}


function uploadFile(obj,that){
	console.log("上传文件的参数", obj);
	let uploadUrl = obj.uploadUrl;
	let filePath = obj.filePath;
	let isSuccess = false;
	let sizeError = 0;
	if (uploadUrl && filePath) {
		let msg = {};
		const uploadTask = uni.uploadFile({
			url: uploadUrl,
			filePath: filePath,
			name: 'fileName',
			header: {
				'Access-Control-Allow-Origin': '*',
				'TOKEN_OA': that.vuex_token,
			},
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200 && uploadFileRes.data.length > 0) {
					let resObj = JSON.parse(uploadFileRes.data);
					if (resObj.code == 200) {
						let _url = that.$u.api.multipartAddress.getFileByPath + resObj.data;
						 msg.url = _url;
						 let suffix = resObj.data.substring(resObj.data.lastIndexOf('.') + 1, resObj.data.length);
						 msg.fileSuffix = suffix;
						 msg.fileName = resObj.data;
						 isSuccess = true;
						 let result= Object.assign(msg,obj);
						 console.log("图片上传结果",result);
						return result;
					} else {
						return null;
					}
				} else {
					return null;
				}
			},
			fail: function() {
				uni.hideLoading();
				return null;
			}
		});
		uploadTask.onProgressUpdate((res) => {
			if (res.totalBytesExpectedToSend > 314572800) {
				sizeError = 1;
				uploadTask.abort();
				utilAlert("文件大小不能超过300M");
				return null;
			} else {
				msg.fileSize =byteConvert(res.totalBytesExpectedToSend);
			}
		});
	} else {
		return null;
	}
}



var faceUtils = {
	alt: [
		'[微笑]',
		'[嘻嘻]',
		'[哈哈]',
		'[可爱]',
		'[可怜]',
		'[挖鼻]',
		'[吃惊]',
		'[害羞]',
		'[挤眼]',
		'[闭嘴]',
		'[鄙视]',
		'[爱你]',
		'[泪]',
		'[偷笑]',
		'[亲亲]',
		'[生病]',
		'[太开心]',
		'[白眼]',
		'[右哼哼]',
		'[左哼哼]',
		'[嘘]',
		'[衰]',
		'[委屈]',
		'[吐]',
		'[哈欠]',
		'[抱抱]',
		'[怒]',
		'[疑问]',
		'[馋嘴]',
		'[拜拜]',
		'[思考]',
		'[汗]',
		'[困]',
		'[睡]',
		'[钱]',
		'[失望]',
		'[酷]',
		'[色]',
		'[哼]',
		'[鼓掌]',
		'[晕]',
		'[悲伤]',
		'[抓狂]',
		'[黑线]',
		'[阴险]',
		'[怒骂]',
		'[互粉]',
		'[心]',
		'[伤心]',
		'[猪头]',
		'[熊猫]',
		'[兔子]',
		'[ok]',
		'[耶]',
		'[good]',
		'[NO]',
		'[赞]',
		'[来]',
		'[弱]',
		'[草泥马]',
		'[神马]',
		'[囧]',
		'[浮云]',
		'[给力]',
		'[围观]',
		'[威武]',
		'[奥特曼]',
		'[礼物]',
		'[钟]',
		'[话筒]',
		'[蜡烛]',
		'[蛋糕]'
	],
	faces: function() {
		let self = this;
		let arr = {};
		for (let i = 0; i < self.alt.length; i++) {
			//arr[self.alt[i]] = "./static/emoji/" + i + ".gif";   //表情加载不出来,请试试这行代码
			arr[self.alt[i]] = "/static/emoji/" + i + ".gif";
		}
		return arr;
	},
	emojiList: function() {
		let self = this;
		let length = Math.ceil(self.alt.length / 24);
		let arr = new Array(length);
		for (let j = 0; j < length; j++) {
			let subArr = [];
			for (var i = j * 24; i < 24 * (j + 1); i++) {
				if (i > self.alt.length - 1) {
					break;
				}
				let obj = {
					"url": i + '.gif',
					"alt": self.alt[i]
				}
				subArr.push(obj)
			}
			arr[j] = subArr;
		}
		return arr;
	}
};

function transform(content, fileSize, fileSuffix) {
	if (fileSize === undefined) {
		fileSize = '';
	}
	if (fileSuffix === undefined) {
		fileSuffix = '';
	}
	let html = function(end) {
		return new RegExp('\\n*\\[' + (end || '') +
			'(code|pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)]\\n*',
			'g');
	};
	let fa = this.faceUtils.faces();
	if (content) {
		content = content
			.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/'/g, '&#39;')
			.replace(/"/g, '&quot;') // XSS
			//.replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2')
			// 转义表情
			.replace(/face\[([^\s\[\]]+?)]/g, function(face) {
				let alt = face.replace(/^face/g, '');
				/* alt="' + fa[alt] + '" title="' + fa[alt] + */
				return '<img class="emoji" style="width:28rpx;height:28rpx;"  src="' + fa[alt] + '"/>';
			})
			// 转义图片
			.replace(/img\[([^\s]+?)]/g, function(img) {
				let href = img.replace(/(^img\[)|(]$)/g, '');
				return '<img class="message-img" src="' + href + '" alt="消息图片不能加载">';
			})
			// 转义文件
			.replace(/file\([\s\S]+?\)\[[\s\S]*?]/g, function(str) {
				let href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
				let text = (str.match(/\)\[([\s\S]*?)]/) || [])[1];
				if (!href) return str;
				/*  return '<div class="flex"><div><i class="iconfont icon-excel" class="icon"></i></div>' +
				    '<div class="flex-file"><a  href="' + href + '">' + (text || href) + '</a>' +
				    '<p style="text-align: right">10kb</p></div></div>';*/
				return '<div class="flex"><i class="iconfont icon-xiazai-yun"></i><a class="message-file"  href="' +
					href + '">' + (text || href) + '</a><span>' + fileSize + '</span></div>'
			})
			// 转义音频
			.replace(/audio\[([^\s]+?)]/g, function(audio) {
				return '<div class="message-audio" data-src="' + audio.replace(/(^audio\[)|(]$)/g, '') +
					'"><i class="layui-icon">&#xe652;</i><p>音频消息</p></div>';
			})
			// 转义视频
			.replace(/video\[([^\s]+?)]/g, function(video) {
				return '<div class="message-video"  data-src="' + video.replace(/(^video\[)|(]$)/g, '') +
					'"><i class="layui-icon">&#xe652;</i></div>';
			})
			// 转义链接
			.replace(/a\([\s\S]+?\)\[[\s\S]*?]/g, function(str) {
				let href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
				let text = (str.match(/\)\[([\s\S]*?)]/) || [])[1];
				if (!href) return str;
				return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
			})
			.replace(html(), '<$1 $2>')
			.replace(html('/'), '</$1>') // 转移HTML代码
			.replace(/\n/g, '<br>'); // 转义换行
	}
	return content;
}


	//跳转聊天窗口
function linkToChatting(groupInfo,that) {
	  let chatGroupId=groupInfo.id;
	  let groupType=groupInfo.chatGroupType;
	  let currentUserId=groupInfo.createUser;
	  //重置未读信息数量
	  let paramData={"chatGroupId":chatGroupId,"userId":currentUserId,"groupType":groupType};
	  that.$u.api.chatGroup.activeHiddenFlag(paramData).then(res => {	
	    if (res.code===200) {
	      let param="?chatGroupId="+chatGroupId;
	      let _url="/pages/chat/chatGroup/chatting";
	      let chatUrl=_url+param;
	      uni.navigateTo({
	        url: chatUrl,
	        success() {
				that.$u.api.chatGroup.clearUnReadNum(param).then(res => {	
				  console.log("重置未读信息数量响应结果",res);
				}).catch(res => {
				  console.log("清除未读数量接口请求失败");
				});
	        }
	      });
	    }
	    else{
	      console.log("清除未读数量失败",res);
	      that.globalUtil.utilAlert(res.data.msg,"none");
	      uni.hideLoading();
	      return;
	    }
	    // 获得数据
	  }).catch(res => {
	    // 失败进行的操作
	    console.log("清除未读数量接口请求失败");
	  });
	}


function uniCopy({content,success,error}) {
	if(!content) return error('复制的内容不能为空 !')
	content = typeof content === 'string' ? content : content.toString() // 复制内容，必须字符串，数字需要转换为字符串
	/**
	 * 小程序端 和 app端的复制逻辑
	 */
	//#ifndef H5
	uni.setClipboardData({
		data: content,
		success: function() {
			success("复制成功~")
			console.log('success');
		},
		fail:function(){
			success("复制失败~")
		}
	});
	//#endif
	
	/**
	 * H5端的复制逻辑
	 */
	// #ifdef H5
	if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
		// 不支持
		error('浏览器不支持')
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	if(result){
		success("复制成功~")
	}else{
		error("复制失败，请检查h5中调用该方法的方式，是不是用户点击的方式调用的，如果不是请改为用户点击的方式触发该方法，因为h5中安全性，不能js直接调用！")
	}	
	textarea.remove()
	// #endif
}


function parseTime(timeStr){
	let t= timeStr.replace(/-/g,"/");
	let date=new Date(t);
	console.log("日期格式的字符串转换为时间",date);
	return date;
	//return date.getTime();
}


module.exports = {
	utilAlert: function (msg, iconType) {
			return utilAlert(msg, iconType);
	},
	utilLoading:function (tip,mask){
	    return utilLoading(tip, mask);
	},
	palyMsgTips:function(index){
		return palyMsgTips(index);	
	},
	palyMsgTipSelected:function(that,chatGroupId){
		return palyMsgTipSelected(that,chatGroupId);
	},
	clearVuex:function(that){
		return clearVuex(that);
	},
	clearStorageVuex:function(that){
		return clearStorageVuex(that);
	},
	
	byteConvert:function(bytes){
		return byteConvert(bytes);
	},
	uploadFile: function(obj,that){
		  uploadFile(obj,that);
	},
	faceUtils: faceUtils,
	transform: transform,
	linkToChatting:function(chatGroup,that){
		return linkToChatting(chatGroup,that);
	},
	uniCopy:function({content,success,error}){
		return uniCopy({content,success,error});
	},
	parseTime:function(timeStr){
		return parseTime(timeStr);
	}
}	
